package hx.bean;

import hx.config.Global;

import java.util.Iterator;
import java.util.LinkedHashMap;

/**
 * 封装排序参数
 *
 * @author HX<titanrain@163.com>
 */
public class SortParam {

    private LinkedHashMap<String, String> orderBy = new LinkedHashMap<String, String>();

    public SortParam() {

    }

    public SortParam(String sortNames, String sortValues) {
        if (sortNames != null && !"".equals(sortNames) && sortValues != null && !"".equals(sortValues)) {
            String[] sortNameArr = sortNames.split(Global.paramSplit);
            String[] sortValueArr = sortValues.split(Global.paramSplit);
            for (int i = 0; i < sortNameArr.length; i++) {
                safeAdd(sortNameArr[i], sortValueArr[i]);
            }
        }
    }

    public SortParam append(String sortName, String sortValue) {
        safeAdd(sortName, sortValue);
        return this;
    }

    private void safeAdd(String sortName, String sortValue) {
        String tmpSortName = sortName.trim();
        if (sortName != null && !"".equals(tmpSortName)) {
            orderBy.put(tmpSortName, sortValue);
        }
    }

    public String orderByStr(String alias) {
        if (orderBy == null || orderBy.isEmpty()) {
            return "";
        }
        String a;
        if (alias != null && !alias.equals("")) {
            a = alias + ".";
        } else {
            a = "";
        }
        StringBuffer bufOrderBy = new StringBuffer(" ORDER BY ");
        Iterator<String> it = orderBy.keySet().iterator();
        while (it.hasNext()) {
            String key = it.next();
            String value = orderBy.get(key);
            bufOrderBy.append(a).append(key).append(" ").append(value).append(",");
        }
        bufOrderBy.deleteCharAt(bufOrderBy.length() - 1);
        return bufOrderBy.toString();
    }

    /**
     * data format: ORDER BY id desc, name asc
     */
    public String orderByStr() {
        return orderByStr("");
    }

}
